package com.TeacherInfoServer.listener;

import com.TeacherInfoServer.exception.JobNumberRepeatedDetailException;
import com.TeacherInfoServer.exception.RecordExistDetailException;
import com.TeacherInfoServer.exception.TeacherNameNotExistException;
import com.TeacherInfoServer.pojo.entity.LearningExperience;
import com.TeacherInfoServer.pojo.entity.Teacher;
import com.TeacherInfoServer.pojo.excelImport.LearningExperienceExcel;
import com.TeacherInfoServer.common.service.CommentService;
import com.TeacherInfoServer.common.service.LearningExperienceService;
import com.TeacherInfoServer.common.service.TeacherService;
import com.TeacherInfoServer.common.service.TypeInfoService;
import com.TeacherInfoServer.utils.ExcelFormatDateUtil;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import jakarta.validation.ConstraintViolation;
import jakarta.validation.ConstraintViolationException;
import jakarta.validation.Validator;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;



    @Data
    @Slf4j
    @Component
    public class LearningExperienceListener implements ReadListener<LearningExperienceExcel> {
        @Autowired
        public LearningExperienceService learningExperienceService;
        @Autowired
        public TeacherService teacherService;
        @Autowired
        public TypeInfoService typeInfoService;
        @Autowired
        public CommentService commentService;
        @Autowired
        private Validator validator;
        private final List<LearningExperience> learningExperienceList = new ArrayList<>();
        private final List<LearningExperience> updateList = new ArrayList<>();
        private final List<LearningExperience> addList = new ArrayList<>();
        private final Set<LearningExperienceExcel> learningExperienceSet = new HashSet<>();
        private Integer record;

        @Override
        public void invoke(LearningExperienceExcel learningExperienceExcel, AnalysisContext analysisContext) {
            Set<ConstraintViolation<LearningExperienceExcel>> violations = validator.validate((learningExperienceExcel));
            if (violations.isEmpty()){
                // 格式化 GraduationDate
                String formattedGraduationDate = ExcelFormatDateUtil.formatDate(learningExperienceExcel.getGraduationDate());
                if (formattedGraduationDate == null) {
                    throw new IllegalArgumentException("日期格式无效: " + learningExperienceExcel.getGraduationDate());
                }

                if(teacherService.getOne(learningExperienceExcel.getTeacherId()).getData() != null) {
                    Teacher teacher = commentService.getByTeacherId(learningExperienceExcel.getTeacherId());
                    if(teacher != null && teacher.getTeacherName().equals(learningExperienceExcel.getTeacherName())) {
                        if(!learningExperienceSet.contains(learningExperienceExcel)) {
                            LearningExperience learningExperience = new LearningExperience(
                                    null,
                                    learningExperienceExcel.getTeacherId(),
                                    typeInfoService.getOneId("学位类型", learningExperienceExcel.getDegreeValue()),
                                    learningExperienceExcel.getGraduationSchool(),
                                    learningExperienceExcel.getMajor(),
                                    formattedGraduationDate // 使用格式化后的日期
                            );
                            learningExperienceList.add(learningExperience);
                            learningExperienceSet.add(learningExperienceExcel);
                        } else {
                            throw new RecordExistDetailException("表中存在完全相同记录");
                        }
                    } else {
                        throw new TeacherNameNotExistException("表中教师学号:" + learningExperienceExcel.getTeacherId() + "教师姓名:" + learningExperienceExcel.getTeacherName() + "与系统中的不匹配");
                    }
                } else {
                    throw new JobNumberRepeatedDetailException("教师工号:" + learningExperienceExcel.getTeacherId() + "不存在");
                }
            } else {
                String errorMessage = violations.iterator().next().getMessage();
                throw new ConstraintViolationException(errorMessage, violations);
            }
        }



        @Override
        public void doAfterAllAnalysed(AnalysisContext analysisContext) {
            List<LearningExperience> learningExperiences = learningExperienceService.list();
            learningExperienceList.forEach(learningExperience -> {
                Optional<LearningExperience> learningExperienceOptional = learningExperiences.stream()
                        .peek(dbLearningExperience -> dbLearningExperience.setId(null))
                        .filter(learningExperience::equals)
                        .findFirst();
                learningExperienceOptional.ifPresent(dbLearningExperience -> log.info("记录已存在数据库:{}", dbLearningExperience));
                if(learningExperienceOptional.isEmpty()) {
                    addList.add(learningExperience);
                }
            });
            List<LearningExperience> mergedList = Stream.concat(updateList.stream(), addList.stream()).collect(Collectors.toList());
            learningExperienceService.saveOrUpdateBatch(mergedList);
            setRecord(mergedList.size());
            initList();
        }

        public void initList() {
            learningExperienceList.clear();
            updateList.clear();
            addList.clear();
            learningExperienceSet.clear();
        }
    }